package com.flyox.game.militarychess.client.view;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MediaTracker;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.audio.AudioStream;

import com.flyox.game.militarychess.CONSTS;
import com.flyox.game.militarychess.bean.ChessMan;
import com.flyox.game.militarychess.bean.Position;
import com.flyox.game.militarychess.bean.ChessMan.NAME;
import com.flyox.game.militarychess.client.services.DataService;
import com.flyox.game.militarychess.message.ChessPackage;
import com.flyox.game.militarychess.message.Request;
import com.flyox.game.militarychess.service.ChessService;
import com.flyox.game.militarychess.service.CommonLayoutService;
import com.flyox.game.militarychess.util.Secret;
import com.flyox.game.militarychess.util.SerialUtil;

public class DeskLayoutJPanel extends javax.swing.JPanel implements MouseListener, MouseMotionListener {

	private static final long serialVersionUID = -46770431996594377L;
	private final Logger logger = LoggerFactory.getLogger(getClass());
	BufferedImage baseImage = null;
	MediaTracker tracker;

	ChessMan[][] deskLayout = null;
	public ChessManPanel[][] chessManPanel = new ChessManPanel[13][20];
	CommonLayoutService commonLayoutService = new CommonLayoutService();
	ChessFrame parent = null;
	public ChessManPanel selectedChessManPanel = null;// 第一次点击选中的棋子
	public ChessManPanel toChessManPanel = null;// 第二次点击选中的棋子
	AudioStream musicSeat;
	ChessService chessService = new ChessService();
	DataService dataService = new DataService();

	public DeskLayoutJPanel(ChessFrame parent) {
		super();
		this.parent = parent;
		ChessMan[][] defalutLayout = commonLayoutService.getDefaultPlayerLayout(dataService.getPlayer().getSeatName());// 取得默认本地布局
		deskLayout = dataService.getLayout();// 服务端返回的全局布局
		commonLayoutService.copyLayout(defalutLayout, deskLayout,dataService.getPlayer().getSeatName());// 合并本地和服务端布局
		initGUI();
	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D) g;
		g2d.drawImage(baseImage, 0, 0, this);
		// this.setOpaque( false );
	}

	private int x_off, y_off;

	private void getChessPos(int row, int col) {
		if (row <= 5) {
			y_off = 50 + 39 * row;
		} else if (row == 6) {
			y_off = 325;
		} else {
			y_off = 130 + 39 * row;
		}
		//
		if (col <= 4) {
			x_off = 70 + 39 * col;
		} else if (col <= 9) {
			x_off = 73 + 39 * col;
		} else if (col <= 14) {
			x_off = 73 + 39 * col;
		} else if (col <= 19) {
			x_off = 73 + 39 * col;
		}

	}

	/**
	 * 判断鼠标点击时，是否选中棋子
	 * 
	 * @param x
	 * @param y
	 * @return false ignore
	 */
	private Position posToRowCol(int x, int y) {
		if (x < 70 || y < 50 || x > 850 || y > 616) {
			return null;
		}
		if (x > 660) {
			x -= 5;
		}
		int row = 0, col = 0;
		col = (x - 70) / 39;
		if (y < 50 + 39 * 6) {
			row = (y - 50) / 39;
		} else if (y > 400) {
			row = (y - 130) / 39;
		} else if (y > 325 && y < 350) {
			row = 6;
		}
		logger.info("row:" + row + " col:" + col);
		return new Position(row, col);
	}

	public void reDrawLayout() {
		deskLayout = dataService.getLayout();
		this.removeAll();
		for (int i = 0; i < deskLayout.length; i++) {
			for (int j = 0; j < deskLayout[i].length; j++) {
				chessManPanel[i][j] = null;
				if (deskLayout[i][j] == null) {
					continue;
				}
				if (deskLayout[i][j].getName() == NAME.EMPTY) {
					continue;
				}
				getChessPos(i, j);
				chessManPanel[i][j] = new ChessManPanel(this, deskLayout[i][j]);
				chessManPanel[i][j].setBounds(x_off, y_off, 36, 27);
				this.add(chessManPanel[i][j]);
			}
		}

		this.repaint();
	}

	private void initGUI() {
		this.setLayout(null);
		try {
			baseImage = ImageIO.read(this.getClass().getResource("/com/flyox/game/militarychess/client/res/img/chessboard.gif"));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		addMouseListener(this);
		addMouseMotionListener(this);

		for (int i = 0; i < deskLayout.length; i++) {
			for (int j = 0; j < deskLayout[i].length; j++) {
				if (deskLayout[i][j] == null) {
					continue;
				}
				if (deskLayout[i][j].getName() == NAME.EMPTY) {
					continue;
				}
				getChessPos(i, j);
				ChessManPanel cmp = new ChessManPanel(this, deskLayout[i][j]);
				cmp.setBounds(x_off, y_off, 36, 27);
				this.add(cmp);
			}
		}
		parent.getJButtonReady().setEnabled(true);// 是完成调度按钮有效
	}

	public void mouseClicked(MouseEvent e) {
		if (selectedChessManPanel != null) {
			int x = e.getX();
			int y = e.getY();
			if (x < 70 || y < 50 || x > 850 || y > 616) {
				return;
			}
			Position toPos = posToRowCol(x, y);
			// 不能移动到特殊位置
			if (toPos.row == 6 && (toPos.col == 1 || toPos.col == 3 || toPos.col == 6 || toPos.col == 8 || toPos.col == 11 || toPos.col == 13 || toPos.col == 16 || toPos.col == 18)) {
				return;
			}

			deskLayout = dataService.getLayout();
			if (deskLayout[toPos.row][toPos.col] == null && chessService.canMoveHere(deskLayout, selectedChessManPanel.cm, toPos)) {
				System.out.println("check pos OK to=" + toPos.toString());
				// begin move
				ChessPackage cp = new ChessPackage(CONSTS.CMD_SEC, dataService.getPlayerID());
				Request request = new Request();
				request.setCommand(CONSTS.CMD_SEC_MOVE);
				request.setFrom(commonLayoutService.revertPosition(selectedChessManPanel.cm.getPosition(),dataService.getPlayer().getSeatName()));
				request.setTo(commonLayoutService.revertPosition(toPos,dataService.getPlayer().getSeatName()));
				byte[] serRequest = null;
				try {
					serRequest = SerialUtil.enSerial(request);
				} catch (IOException e1) {
					e1.printStackTrace();
					return;
				}
				serRequest = Secret.encryptMsg(serRequest, dataService.getPlayer().getDesKey());
				cp.setContent(serRequest);

				parent.updateSysMessage("走棋。选中第二个位置。等待回复");
				selectedChessManPanel.jLabelChess.setBorder(BorderFactory.createCompoundBorder(null, null));
				// 发送请求
				parent.control.sendRequest(cp);
				parent.endTimeCount();//
			}
		}
	}

	public void mouseEntered(MouseEvent e) {

	}

	public void mouseExited(MouseEvent e) {

	}

	public void mousePressed(MouseEvent e) {

	}

	public void mouseReleased(MouseEvent e) {

	}

	public void mouseDragged(MouseEvent e) {

	}

	/**
	 * 显示坐标
	 */
	public void mouseMoved(MouseEvent e) {
		// int x=e.getX();
		// int y=e.getY();
		// if(x<70||y<50||x>850||y>616){
		// return ;
		// }
		// Position p=posToRowCol(x,y);
		// String msg="x="+x+" y="+y+" row="+p.row+" col="+p.col;
		// parent.updatePosMessage(msg);
	}


}
